package com.zhongjian.technologycal.mall.activity.personal.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.adapter.AllOrderAdapter;
import com.zhongjian.technologycal.mall.adapter.CourseListAdapter;
import com.zhongjian.technologycal.mall.base.BaseFragment;
import com.zhongjian.technologycal.mall.bean.MyCourseBean;
import com.zhongjian.technologycal.mall.bean.OrdersModelBean;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.LoadingTip;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2017/12/15.
 * 待开课的课程列表
 */

public class WaitCourseListFragment extends BaseFragment {
    public static final String CATEGORY_NAME = "com.nanchen.aiyagirl.module.category.CategoryFragment.CATEGORY_NAME";
    @BindView(R.id.lv_course_recyclerview)
    RecyclerView lv_course_recyclerview;
    @BindView(R.id.course_loadedTip)
    LoadingTip loadingTip;
    @BindView(R.id.all_order_RefreshLayout)
    RefreshLayout refreshLayout;
    private CourseListAdapter courseListAdapter;
    private List<MyCourseBean> listItems;
    private int page = 0;
    private int pageNum =10;
    public static String userName;
    @Override
    protected void initView() {
        initRequest();
        listItems = new ArrayList<>();
        courseListAdapter = new CourseListAdapter(listItems);
        lv_course_recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        lv_course_recyclerview.setAdapter(courseListAdapter);
        courseListAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                page = 0;
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initRequest();
                        refreshlayout.finishRefresh();
                        refreshlayout.setLoadmoreFinished(false);
                    }
                }, 1000);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(final RefreshLayout refreshlayout) {
                page ++ ;
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initRequest();
                        refreshlayout.finishLoadmore();
                    }
                }, 1000);
            }
        });

    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_course_list;
    }


    public static WaitCourseListFragment newInstance(String mCategoryName) {
        WaitCourseListFragment categoryFragment = new WaitCourseListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CATEGORY_NAME, mCategoryName);
        categoryFragment.setArguments(bundle);
        return categoryFragment;
    }

    @Override
    public void initPresenter() {
//        initRequest();
    }

    /**
     * 数据列表请求
     */
    private void initRequest(){
        if(!NetWorkUtils.isNetConnected(getActivity())){
            loadingTip.setLoadingTip(LoadingTip.LoadStatus.error);
            return;
        }
        HttpRetrofitClient.getInstance(getActivity())
                .getUrlRequestMyCourse(UserUtils.getUserToken(),
                        "wait",page,pageNum, new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                                loadingTip.setLoadingTip(LoadingTip.LoadStatus.loading);
                            }
                            @Override
                            public void onCompleted() {
                                if(listItems.size() <= 0){
                                    loadingTip.setLoadingTip(LoadingTip.LoadStatus.empty);
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                loadingTip.setLoadingTip(LoadingTip.LoadStatus.sereverError);
                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                loadingTip.setLoadingTip(LoadingTip.LoadStatus.finish);
                                try {
                                    Gson gson = new Gson();
                                    JSONObject jsonObject = new JSONObject(responseBody.string());
                                    if(jsonObject.optInt("error_code") == 0){
                                        JSONArray jsonArray = jsonObject.optJSONArray("data");
                                        List<MyCourseBean> forlist = gson.fromJson(jsonArray.toString(),new TypeToken<List<MyCourseBean>>(){}.getType());
                                        setData(forlist);
                                    }else if(jsonObject.optInt("error_code") == 3){
                                        Intent intent = new Intent();
                                        intent.setAction("com.broadcast.info_out_line");
                                        getActivity().sendBroadcast(intent);
                                    }
                                    else{
                                        ToastUitl.showShort(""+jsonObject.optString("error_message"));
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });
    }

    private void setData(List<MyCourseBean> foreshowList) {
        if(page == 0){
            listItems.clear();
        }
        for (MyCourseBean vo : foreshowList) {
            listItems.add(vo);
        }
        courseListAdapter.notifyDataSetChanged();
    }

}
